package com.kuang.Controller;

import com.alibaba.fastjson.JSON;
import com.kuang.pojo.Token;
import com.kuang.pojo.User;
import com.kuang.utils.HttpClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/wechat")
public class WechatScanLoginController {

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @GetMapping("/vxlogin")
    public String login(HttpServletRequest request) {
        System.out.println("====================qqq=================");
        //获取到code值
        String code = request.getParameter("code");
        //判断code值是否为空
        if (code == null) {
            System.out.println("用户禁止授权");
            return "login";
        }
        try {
            //通过 code 获取 access_token
            String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxddc93348f7d8ffdd" +
                    "&secret=197b8ca2b57b773f6cb51d27ecd2ca27&code=" + code + "&grant_type=authorization_code";

            //发送请求
            HttpClient client = new HttpClient(token_url);
            //发送get请求
            client.get();
            //获取到请求的结果
            String token_content = client.getContent();
            //把请求的结果转换成对象
            Token token = JSON.parseObject(token_content, Token.class);

            //获取到接口调用凭证
            //获取个人信息
            String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+token.getAccess_token()+"&openid="+token.getOpenid();
            HttpClient client1 = new HttpClient(user_url);
            String user_content = client1.getContent();
            User user = JSON.parseObject(user_content, User.class);
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}
